package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hy.corecode.idgen.WFGIdGenerator;
import io.xxx.xbutler.data.RobotContactMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.RobotContact;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 标签下添加多个好友回调
 *
 * <pre>
 * {
 *     "nType": 2007,
 *     "vcMerchantNo": "",
 *     "vcRobotWxId": "",
 *     "vcRobotSerialNo": "",
 *     "vcSerialNo": "",
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "Data": {
 *         "nTagId": 12,
 *         "vcTagName": "",
 *         "vcBase64TagName": "",
 *         "Friends": [
 *             {
 *                 "vcFriendWxId": "",
 *                 "vcFriendSerialNo": ""
 *             }
 *         ]
 *     }
 * }
 * </pre>
 */
@Slf4j
@Component
public class _2007Handler implements CallbackHandler {

    @Resource
    private WFGIdGenerator idGenerator;

    @Resource
    private RobotContactMapper robotContactMapper;

    @Override
    public String name() {
        return "标签下添加多个好友回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 2007;
    }

    @Override
    public void handle(Callback callback) {
        LocalDateTime now = LocalDateTime.now();
        JSONObject data = (JSONObject) callback.getData();
        String robotId = callback.getRobotId();
        String robotSerialNo = callback.getRobotSerialNo();
        JSONArray friends = data.getJSONArray("Friends");
        List<RobotContact> robotContacts = friends.stream()
                .map(it -> {
                    JSONObject friend = JSONObject.from(it);
                    return new RobotContact()
                            .setId(idGenerator.next())
                            .setRobotId(robotId)
                            .setRobotSerialNo(robotSerialNo)
                            .setContactId(friend.getString("vcFriendWxId"))
                            .setContactSerialNo(friend.getString("vcFriendSerialNo"))
                            .setCreatedTime(now)
                            .setUpdatedTime(now);
                })
                .toList();
        robotContactMapper.insert(robotContacts);
    }
}
